package stud.g01.problem.npuzzle;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public final class DatabaseLoader {
    public static final byte[] costTable_15_puzzle_0 = new byte[4096],
            costTable_15_puzzle_1 = new byte[16777216],
            costTable_15_puzzle_2 = new byte[16777216];

    static {
        try {
            loadCcostTable("database/db1.db", costTable_15_puzzle_1);
            loadCcostTable("database/db2.db", costTable_15_puzzle_2);
            loadCcostTable("database/db0.db", costTable_15_puzzle_0);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        loadStreamCostTable("database/15-puzzle-663-0.db", costTable_15_puzzle_0);
//        loadStreamCostTable("database/15-puzzle-663-1.db", costTable_15_puzzle_1);
//        loadStreamCostTable("database/15-puzzle-663-2.db", costTable_15_puzzle_2);
    }

    private static void loadCcostTable(final String filename,
                                       final byte[] costTable) throws  IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        String[] numbers = content.split("\\s+");

        for (int i = 0; i < costTable.length; i++) {
            costTable[i] = Byte.parseByte(numbers[i]);
        }
    }

    private static void loadStreamCostTable(final String filename,
                                            final byte[] costTable) {
        InputStream is = DatabaseLoader.class.getResourceAsStream(filename);
        DataInputStream dis = null;
        try {
            if (is == null) {
                is = new FileInputStream(filename);
            }
            dis = new DataInputStream(new BufferedInputStream(is));
            int i = 0;
            while (true) {
                costTable[i++] = dis.readByte();
            }
        } catch (final EOFException ignored) {

        } catch (final FileNotFoundException fnfe) {
            System.err.println("Error: Cannot find file " + filename + ".");
            System.exit(1);
        } catch (final IOException ioe) {
            System.err.println("Error: Cannot read from file " + filename + ".");
            System.exit(1);
        } finally {
            try {
                if (dis != null) {
                    dis.close();
                }
            } catch (final IOException ignored) { }
        }
    }
}
